<template>
  <div class="addTestPaper">
    <div class="container">
      <div class="addTestTitle">
        <h2> {{ type=='add'?'添加':'编辑' }}试卷</h2>
        <el-button
          plain
          class="backBtn"
          @click="backBtn"
        >返回</el-button>
      </div>

      <div class="addTestForm">
        <el-form
          :rules="rules"
          :model="addTestForm"
          label-width="auto"
          ref="addTestFormRef"
        >
          <el-form-item
            label="试卷名称："
            prop="paperTitle"
          >
            <el-input
              v-model="addTestForm.paperTitle"
              placeholder="请输入试卷名称"
              :maxlength="50"
            />
          </el-form-item>

          <el-form-item
            label="试卷类型："
            prop="paperType"
          >
            <el-radio-group
              v-model="addTestForm.paperType"
              class="ml-4"
              @change="changePaperType"
            >
              <el-radio
                :label="0"
                size="large"
              >统一题目</el-radio>
              <el-radio
                :label="1"
                size="large"
              >随机题目</el-radio>
            </el-radio-group>
          </el-form-item>

          <div class="questionSet">
            <el-form-item
              label="全部题数："
              style="width: 287px;"
            >
              <span
                style="font-size: 16px;color: #343957;">{{ questionCount }}道</span>
            </el-form-item>

            <el-form-item label="总分值：">
              <span
                style="font-size: 16px;color: #343957;">{{ totalScore }}分</span>
            </el-form-item>

          </div>

          <div class="questionSet">
            <el-form-item
              label="单选题数："
              prop="singleChoice"
            >
              <el-input
                v-model="addTestForm.singleChoice"
                placeholder="请输入数量"
                @input="clearZero"
              />
            </el-form-item>

            <el-form-item
              label="每题分值："
              style="margin-left: 25px;"
              v-if="addTestForm.singleChoice && !(addTestForm.singleChoice=='0')"
              prop="singleChoiceValue"
            >
              <el-input
                v-model="addTestForm.singleChoiceValue"
                placeholder="请输入分数"
              />
            </el-form-item>

            <el-button
              class="chooseQuestionBtn1"
              :class="{'chooseQuestionBtn2':selectedSingleChoice}"
              plain
              :disabled="addTestForm.singleChoice=='' || addTestForm.singleChoiceValue == ''"
              v-if="addTestForm.paperType==0 && addTestForm.singleChoiceValue"
              @click="singleChoose"
            >
              选择题目
            </el-button>
          </div>

          <div class="questionSet">
            <el-form-item
              label="多选题数："
              prop="multipleChoice"
            >
              <el-input
                v-model="addTestForm.multipleChoice"
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item
              label="每题分值："
              style="margin-left: 25px;"
              v-if="addTestForm.multipleChoice && !(addTestForm.multipleChoice=='0')"
              prop="multipleChoiceValue"
            >
              <el-input
                v-model="addTestForm.multipleChoiceValue"
                placeholder="请输入分数"
              />
            </el-form-item>

            <el-button
              class="chooseQuestionBtn1"
              :class="{'chooseQuestionBtn2':selectedMultipleChoice}"
              plain
              v-if="addTestForm.paperType==0 && addTestForm.multipleChoiceValue"
              :disabled="addTestForm.multipleChoice=='' || addTestForm.multipleChoiceValue == ''"
              @click="multipeChoice"
            >
              选择题目
            </el-button>
          </div>

          <div class="questionSet">
            <el-form-item
              label="判断题数："
              prop="judgeChoice"
            >
              <el-input
                v-model="addTestForm.judgeChoice"
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item
              label="每题分值："
              style="margin-left: 25px;"
              v-if="addTestForm.judgeChoice && !(addTestForm.judgeChoice=='0')"
              prop="judgeChoiceValue"
            >
              <el-input
                v-model="addTestForm.judgeChoiceValue"
                placeholder="请输入分数"
              />
            </el-form-item>

            <el-button
              class="chooseQuestionBtn1"
              :class="{'chooseQuestionBtn2': selectedJudgeChoice}"
              plain
              v-if="addTestForm.paperType==0 && addTestForm.judgeChoiceValue"
              :disabled="addTestForm.judgeChoice=='' || addTestForm.judgeChoiceValue == ''"
              @click="trueOrFalseChoice"
            >
              选择题目
            </el-button>
          </div>

          <div class="questionSet">
            <el-form-item
              label="填空题数："
              prop="fillChoice"
            >
              <el-input
                v-model="addTestForm.fillChoice"
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item
              label="每题分值："
              style="margin-left: 25px;"
              v-if="addTestForm.fillChoice && !(addTestForm.fillChoice=='0')"
              prop="fillChoiceValue"
            >
              <el-input
                v-model="addTestForm.fillChoiceValue"
                placeholder="请输入分数"
              />
            </el-form-item>

            <el-button
              class="chooseQuestionBtn1"
              :class="{'chooseQuestionBtn2': selectedFillChoice}"
              plain
              v-if="addTestForm.paperType==0 && addTestForm.fillChoiceValue"
              :disabled="addTestForm.fillChoice=='' || addTestForm.fillChoiceValue == ''"
              @click="completionChoice"
            >
              选择题目
            </el-button>
          </div>

          <div class="questionSet">
            <el-form-item
              label="论述题数："
              prop="discussChoice"
            >
              <el-input
                v-model="addTestForm.discussChoice"
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item
              label="每题分值："
              style="margin-left: 25px;"
              v-if="addTestForm.discussChoice && !(addTestForm.discussChoice=='0')"
              prop="discussChoiceValue"
            >
              <el-input
                v-model="addTestForm.discussChoiceValue"
                placeholder="请输入分数"
              />
            </el-form-item>

            <el-button
              class="chooseQuestionBtn1"
              :class="{'chooseQuestionBtn2': selecteddiscussChoice}"
              plain
              v-if="addTestForm.paperType==0 && addTestForm.discussChoiceValue"
              :disabled="addTestForm.discussChoice=='' || addTestForm.discussChoiceValue == ''"
              @click="essayChoice"
            >
              选择题目
            </el-button>
          </div>

        </el-form>

        <div class="operateBox">
          <el-button
            plain
            class="btnCancel"
            @click="cancelAddTest"
          >取消</el-button>
          <el-button
            plain
            class="btnSave"
            @click="confirmAddTest"
          >保存</el-button>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { computed, onBeforeMount, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router';
// 引入存储选中题目id的pinia仓库
import { useDictStore } from '@/store/modules/addtest.js'

// 引入存储试卷信息详情的pinia仓库
import { useTestpaperDetailStore } from '@/store/modules/testpaperdetail.js'
// 引入新增试卷,获取试卷详情信息,修改试卷 的接口
import { addTestPaper, getTestPaperDetail, updateTestPaper } from '@/api/assessment/testpapermanage.js'
import { ElMessage } from 'element-plus';
const router = useRouter()
const route = useRoute()

// 使用存储选中题目id的pinia仓库
const dictStore = useDictStore()

// 使用存储存试卷信息详情的仓库
const testpaperDetailStore = useTestpaperDetailStore()



const paperId = computed(() => route.query.paperId)

const type = computed(() => route.query.type)

const isGetData = computed(() => route.query.isGetData)

// 获取试卷详情信息
if (paperId.value) {
  testpaperDetailStore.getTestPaperDetailData(paperId.value)
}

onBeforeMount(() => {
  // 是编辑的话就先获取信息回显
  if (paperId.value && isGetData.value == 1) {
    dictStore.editQuestion(paperId.value)
  }
})



const addTestForm = ref({
  paperTitle: '',
  paperType: 0,
  singleChoice: '',
  singleChoiceValue: '',
  multipleChoice: '',
  multipleChoiceValue: '',
  judgeChoice: '',
  judgeChoiceValue: '',
  fillChoice: '',
  fillChoiceValue: '',
  discussChoice: '',
  discussChoiceValue: ''
})

const rules = ref({
  paperTitle: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入非空值且不能包含空格'));
        } else if (/\s/.test(value)) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('输入不能包含空格'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  paperType: [
    { required: true, message: '请选择试卷类型', trigger: 'change' }
  ],
  singleChoice: [
    { required: true, message: '请输入单选题数', trigger: 'blur' },

    {
      validator: (rule, value, callback) => {
        console.log(value, "---------------------------")
        if (!(/^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  singleChoiceValue: [
    { required: true, message: '请输入单选题分值', trigger: 'blur' },

    {
      validator: (rule, value, callback) => {
        if (!(/^(?:100(?:\.0)?|\d{1,2}(?:\.\d)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的整数或一位小数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  multipleChoice: [
    { required: true, message: '请输入多选题数', trigger: 'blur' },

    {
      validator: (rule, value, callback) => {

        console.log(value, "---------------------------")
        if (!(/^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  multipleChoiceValue: [
    { required: true, message: '请输入多选题分值', trigger: 'blur' },
    
    {
      validator: (rule, value, callback) => {
        if (!(/^(?:100(?:\.0)?|\d{1,2}(?:\.\d)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的整数或一位小数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  judgeChoice: [
    { required: true, message: '请输入判断题数', trigger: 'blur' },
    
    {
      validator: (rule, value, callback) => {

        console.log(value, "---------------------------")
        if (!(/^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  judgeChoiceValue: [
    { required: true, message: '请输入判断题分值', trigger: 'blur' },
    
    {
      validator: (rule, value, callback) => {
        if (!(/^(?:100(?:\.0)?|\d{1,2}(?:\.\d)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的整数或一位小数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  fillChoice: [
    { required: true, message: '请输入填空题数', trigger: 'blur' },
   
    {
      validator: (rule, value, callback) => {

        console.log(value, "---------------------------")
        if (!(/^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  fillChoiceValue: [
    { required: true, message: '请输入填空题分值', trigger: 'blur' },
    
    {
      validator: (rule, value, callback) => {
        if (!(/^(?:100(?:\.0)?|\d{1,2}(?:\.\d)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的整数或一位小数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  discussChoice: [
    { required: true, message: '请输入论述题数', trigger: 'blur' },
    
    {
      validator: (rule, value, callback) => {

        if (!(/^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],
  discussChoiceValue: [
    { required: true, message: '请输入论述题分值', trigger: 'blur' },
    
    {
      validator: (rule, value, callback) => {
        if (!(/^(?:100(?:\.0)?|\d{1,2}(?:\.\d)?)$/.test(value))) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('只能输入0-100之间的整数或一位小数'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ]

})

// 获取试卷详情信息
async function questionDetail () {
  const res = await getTestPaperDetail(Number(paperId.value))
  if (addTestForm.value.paperId && localStorage.getItem('addTestForm')) {
    addTestForm.value = JSON.parse(localStorage.getItem('addTestForm'))
  } else {
    addTestForm.value = res.data
  }
}


// 页面挂载的时候调用获取试卷详情的方法
onBeforeMount(() => {
  if (paperId.value) {
    questionDetail()
  }
})

// 浏览器刷新，清除本地存储
window.addEventListener('unload', (event) => {

  const addTestForm = {
    paperTitle: '',
    paperType: 0,
    singleChoice: '',
    singleChoiceValue: '',
    multipleChoice: '',
    multipleChoiceValue: '',
    judgeChoice: '',
    judgeChoiceValue: '',
    fillChoice: '',
    fillChoiceValue: '',
    discussChoice: '',
    discussChoiceValue: ''
  }
  dictStore.clearIds()
  localStorage.setItem('addTestForm', JSON.stringify(addTestForm))
})

function changeType () {
  addTestForm.value.singleChoice = Number(addTestForm.value.singleChoice)
  addTestForm.value.multipleChoice = Number(addTestForm.value.multipleChoice)
  addTestForm.value.judgeChoice = Number(addTestForm.value.judgeChoice)
  addTestForm.value.fillChoice = Number(addTestForm.value.fillChoice)
  addTestForm.value.discussChoice = Number(addTestForm.value.discussChoice)
  addTestForm.value.singleChoiceValue = Number(addTestForm.value.singleChoiceValue)
  addTestForm.value.multipleChoiceValue = Number(addTestForm.value.multipleChoiceValue)
  addTestForm.value.judgeChoiceValue = Number(addTestForm.value.judgeChoiceValue)
  addTestForm.value.fillChoiceValue = Number(addTestForm.value.fillChoiceValue)
  addTestForm.value.discussChoiceValue = Number(addTestForm.value.discussChoiceValue)
}

watch(
  addTestForm,
  (newVal, oldVal) => {
    console.log(newVal)
    localStorage.clear()
    localStorage.setItem('addTestForm', JSON.stringify(newVal))
  },
  {
    deep: true
  }
)
onBeforeMount(() => {
  // 如果本地存储有内容，就获取到本地存储的内容赋值给添加表单
  if (localStorage.getItem('addTestForm')) {
    addTestForm.value = JSON.parse(localStorage.getItem('addTestForm'))
  }
})
watch(
  () => route.path,
  (newVal, oldVal) => {
    console.log(newVal, oldVal)
    if (!(newVal == '/assment/choosequestion' && oldVal == '/assment/addtestpaper')) {
      if (!(newVal == '/assment/addtestpaper')) {
        console.log(123)
        try {
          clearData()
        } catch (error) {

        }
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)



const path = ref('')
router.beforeEach((to, from, next) => {
  // 将试卷管理首页的路径存储下来
  path.value = to.path
  next()
})

onUnmounted(() => {
  // 当返回的路径是试卷管理首页时，清空本地存储
  if (path.value == '/assment/testpaper') {
    localStorage.clear()
  }
})




// 总题数
const questionCount = computed(() => {
  let counts = Number(addTestForm.value.singleChoice) +
    Number(addTestForm.value.multipleChoice) +
    Number(addTestForm.value.judgeChoice) +
    Number(addTestForm.value.fillChoice) +
    Number(addTestForm.value.discussChoice)
  if (!counts) {
    return 0
  } else if (counts < 0) {
    return 0
  } else {
    return counts
  }
})
// 总分值
const totalScore = computed(() => {
  let totalScore = Number(addTestForm.value.singleChoiceValue * addTestForm.value.singleChoice) +
    Number(addTestForm.value.multipleChoiceValue * addTestForm.value.multipleChoice) +
    Number(addTestForm.value.judgeChoiceValue * addTestForm.value.judgeChoice) +
    Number(addTestForm.value.fillChoiceValue * addTestForm.value.fillChoice) +
    Number(addTestForm.value.discussChoiceValue * addTestForm.value.discussChoice)
  if (!totalScore) {
    return 0
  } else if (totalScore < 0) {
    return 0
  } else {
    return totalScore
  }
})



function backBtn () {
  router.push({
    path: "testpaper"
  })
}

watch(
  () => addTestForm.value.singleChoice,
  (newVal, oldVal) => {
    if (newVal == "") {
      addTestForm.value.singleChoiceValue = ''
    }
  }
)
watch(
  () => addTestForm.value.multipleChoice,
  (newVal, oldVal) => {
    if (newVal == "") {
      addTestForm.value.multipleChoiceValue = ''
    }
  }
)
watch(
  () => addTestForm.value.judgeChoice,
  (newVal, oldVal) => {
    if (newVal == "") {
      addTestForm.value.judgeChoiceValue = ''
    }
  }
)
watch(
  () => addTestForm.value.fillChoice,
  (newVal, oldVal) => {
    if (newVal == "") {
      addTestForm.value.fillChoiceValue = ''
    }
  })
watch(
  () => addTestForm.value.discussChoice,
  (newVal, oldVal) => {
    if (newVal == "") {
      addTestForm.value.discussChoiceValue = ''
    }
  }
)

const isEcho = ref(true)

// 单选题选择
function singleChoose () {
  console.log(dictStore.singleChoiceIds)
  if (Number(addTestForm.value.singleChoice) < 0) {
    ElMessage({
      message: '单选题数量不能小于等于0道',
      type: 'warning'
    })
  } else if (Number(addTestForm.value.singleChoice) > 100) {
    ElMessage({
      message: '单选题数量不能大于100道',
      type: 'warning'
    })
  }
  else if (Number(addTestForm.value.singleChoiceValue) < 0) {
    ElMessage({
      message: '单选题分值不能小于等于0分',
      type: 'warning'
    })
  } else if (!isInteger(addTestForm.value.singleChoice)) {
    ElMessage({
      message: '单选题数量只能是正整数',
      type: 'warning'
    })
  } else if (!isPositiveNumber(addTestForm.value.singleChoiceValue)) {
    ElMessage({
      message: '单选题分值只能是正整数或小数点后有一位的正小数',
      type: 'warning'
    })
  } else {
    router.push({
      path: 'choosequestion',
      query: {
        type: 0,
        questionCount: addTestForm.value.singleChoice,
        questionScore: addTestForm.value.singleChoiceValue,
        operateType: type.value,
        isEcho: isEcho.value
      }
    })
  }
}

// 多选题选择
function multipeChoice () {
  if (Number(addTestForm.value.multipleChoice) < 0) {
    ElMessage({
      message: '多选题数量不能小于等于0道',
      type: 'warning'
    })
  } else if (Number(addTestForm.value.multipleChoiceValue) < 0) {
    ElMessage({
      message: '多选题分值不能小于等于0分',
      type: 'warning'
    })
  } else if (!isInteger(addTestForm.value.multipleChoice)) {
    ElMessage({
      message: '多选题数量只能是正整数',
      type: 'warning'
    })
  } else if (!isPositiveNumber(addTestForm.value.multipleChoiceValue)) {
    ElMessage({
      message: '多选题分值只能是正整数或小数点后有一位的正小数',
      type: 'warning'
    })
  } else {
    router.push({
      path: 'choosequestion',
      query: {
        type: 1,
        questionCount: addTestForm.value.multipleChoice,
        questionScore: addTestForm.value.multipleChoiceValue,
        operateType: type.value
      }
    })
  }
}

// 判断题选择
function trueOrFalseChoice () {
  if (Number(addTestForm.value.judgeChoice) < 0) {
    ElMessage({
      message: '判断题数量不能小于等于0道',
      type: 'warning'
    })
  } else if (Number(addTestForm.value.judgeChoiceValue) < 0) {
    ElMessage({
      message: '判断题分值不能小于等于0分',
      type: 'warning'
    })
  } else if (!isInteger(addTestForm.value.judgeChoice)) {
    ElMessage({
      message: '判断题数量只能是正整数',
      type: 'warning'
    })
  } else if (!isPositiveNumber(addTestForm.value.judgeChoiceValue)) {
    ElMessage({
      message: '判断题分值只能是正整数或小数点后有一位的正小数',
      type: 'warning'
    })
  } else {
    router.push({
      path: 'choosequestion',
      query: {
        type: 2,
        questionCount: addTestForm.value.judgeChoice,
        questionScore: addTestForm.value.judgeChoiceValue,
        operateType: type.value
      }
    })
  }
}

// 填空题选择
function completionChoice () {
  if (Number(addTestForm.value.fillChoice) < 0) {
    ElMessage({
      message: '填空题数量不能小于等于0道',
      type: 'warning'
    })
  } else if (Number(addTestForm.value.fillChoiceValue) < 0) {
    ElMessage({
      message: '填空题分值不能小于等于0分',
      type: 'warning'
    })
  } else if (!isInteger(addTestForm.value.fillChoice)) {
    ElMessage({
      message: '填空题数量只能是正整数',
      type: 'warning'
    })
  } else if (!isPositiveNumber(addTestForm.value.fillChoiceValue)) {
    ElMessage({
      message: '填空题分值只能是正整数或小数点后有一位的正小数',
      type: 'warning'
    })
  } else {
    router.push({
      path: 'choosequestion',
      query: {
        type: 3,
        questionCount: addTestForm.value.fillChoice,
        questionScore: addTestForm.value.fillChoiceValue,
        operateType: type.value
      }
    })
  }
}

// 论述题选择
function essayChoice () {
  if (Number(addTestForm.value.discussChoice) < 0) {
    ElMessage({
      message: '论述题数量不能小于等于0道',
      type: 'warning'
    })
  } else if (Number(addTestForm.value.discussChoiceValue) < 0) {
    ElMessage({
      message: '论述题分值不能小于等于0分',
      type: 'warning'
    })
  } else if (!isInteger(addTestForm.value.discussChoice)) {
    ElMessage({
      message: '论述题数量只能是正整数',
      type: 'warning'
    })
  } else if (!isPositiveNumber(addTestForm.value.discussChoiceValue)) {
    ElMessage({
      message: '论述题分值只能是正整数或小数点后有一位的正小数',
      type: 'warning'
    })
  } else {
    router.push({
      path: 'choosequestion',
      query: {
        type: 4,
        questionCount: addTestForm.value.discussChoice,
        questionScore: addTestForm.value.discussChoiceValue,
        operateType: type.value
      }
    })
  }
}

function isPositiveNumber (str) {
  // 使用正则表达式匹配正整数或正一位小数的格式
  const positiveNumberPattern = /^(?:0|[1-9]\d*)(?:\.\d)?$/;
  return positiveNumberPattern.test(str);
}

function isInteger (str) {
  // 使用正则表达式匹配整数的格式
  const integerPattern = /^-?\d+$/;
  return integerPattern.test(str);
}



const selectedSingleChoice = computed(() => {
  if (dictStore.singleChoiceIds.length > 0) {
    return true
  } else {
    return false
  }
})
const selectedMultipleChoice = computed(() => {
  if (dictStore.multipleChoiceIds.length > 0) {
    return true
  } else {
    return false
  }
})
const selectedJudgeChoice = computed(() => {
  if (dictStore.judgeChoiceIds.length > 0) {
    return true
  } else {
    return false
  }
})
const selectedFillChoice = computed(() => {
  if (dictStore.fillChoiceIds.length > 0) {
    return true
  } else {
    return false
  }
})
const selecteddiscussChoice = computed(() => {
  if (dictStore.discussChoiceIds.length > 0) {
    return true
  } else {
    return false
  }
})


// 拿到选择问题的id
const chooseQuestion = ref(null)


const addTestFormRef = ref(null)



function confirmAddTest () {

  const singleChoiceIds = dictStore.singleChoiceIds
  const multipleChoiceIds = dictStore.multipleChoiceIds
  const judgeChoiceIds = dictStore.judgeChoiceIds
  const fillChoiceIds = dictStore.fillChoiceIds
  const discussChoiceIds = dictStore.discussChoiceIds

  addTestFormRef.value.validate(async (valid) => {


    if (valid && addTestForm.value.paperType == 0) {
      changeType()
      if (addTestForm.value.singleChoice != 0 && singleChoiceIds.length === 0) {
        return ElMessage({
          type: 'error',
          message: "您预设了单选题数量和分数，但是未选择题目，请检查"
        })
      } else if (addTestForm.value.multipleChoice != 0 && multipleChoiceIds.length === 0) {
        return ElMessage({
          type: 'error',
          message: "您预设了多选题数量和分数，但是未选择题目，请检查"
        })
      } else if (addTestForm.value.judgeChoice != 0 && judgeChoiceIds.length === 0) {
        return ElMessage({
          type: 'error',
          message: "您预设了判断题数量和分数，但是未选择题目，请检查"
        })
      } else if (addTestForm.value.fillChoice != 0 && fillChoiceIds.length === 0) {
        return ElMessage({
          type: 'error',
          message: "您预设了填空题数量和分数，但是未选择题目，请检查"
        })
      } else if (addTestForm.value.discussChoice != 0 && discussChoiceIds.length === 0) {
        return ElMessage({
          type: 'error',
          message: "您预设了论述题数量和分数，但是未选择题目，请检查"
        })
      }
      if (!addTestForm.value.paperId) {
        const res = await addTestPaper(
          {
            ...addTestForm.value,
            singleChoiceIds,
            multipleChoiceIds,
            judgeChoiceIds,
            fillChoiceIds,
            discussChoiceIds,
            totalTopic: questionCount.value,
            totalValue: totalScore.value
          }
        )
        ElMessage({
          message: '新增成功',
          type: 'success'
        })
        router.push({
          path: 'testpaper'
        })
      } else {
        await updateTestPaper({
          ...addTestForm.value,
          singleChoiceIds,
          multipleChoiceIds,
          judgeChoiceIds,
          fillChoiceIds,
          discussChoiceIds,
          totalTopic: questionCount.value,
          totalValue: totalScore.value
        })
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        if (addTestForm.value.paperType == 1) {
          router.push({
            path: 'testpaper'
          })
        } else {
          router.push({
            path: 'testpaper'
          })
        }
      }
      try {
        clearData()
      } catch (error) {

      }
    } else if (valid && addTestForm.value.paperType == 1) {
      changeType()
      if (addTestForm.value.singleChoice == 0 && addTestForm.value.multipleChoice == 0 && addTestForm.value.judgeChoice == 0 && addTestForm.value.fillChoice == 0 && addTestForm.value.discussChoice == 0) {
        return ElMessage({
          type: 'error',
          message: "您未选择任何题型，请检查"
        })
      }
      if (!addTestForm.value.paperId) {
        const res = await addTestPaper(
          {
            ...addTestForm.value,
            singleChoiceIds,
            multipleChoiceIds,
            judgeChoiceIds,
            fillChoiceIds,
            discussChoiceIds,
            totalTopic: questionCount.value,
            totalValue: totalScore.value
          }
        )
        ElMessage({
          message: '新增成功',
          type: 'success'
        })
        router.push({
          path: 'testpaper'
        })
      } else {
        await updateTestPaper({
          ...addTestForm.value,
          singleChoiceIds,
          multipleChoiceIds,
          judgeChoiceIds,
          fillChoiceIds,
          discussChoiceIds,
          totalTopic: questionCount.value,
          totalValue: totalScore.value
        })
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        if (addTestForm.value.paperType == 1) {
          router.push({
            path: 'testpaper'
          })
        } else {
          router.push({
            path: 'testpaper'
          })
        }
      }
      try {
        clearData()
      } catch (error) {

      }
    }
  })
}



// 当选题方式发生变化的时候，直接修改选题方式
async function changePaperType (item) {
  console.log(item)
  localStorage.setItem('addTestForm', JSON.stringify(addTestForm.value))
  if (item == 0) {
    ElMessage({
      message: '试卷类型改为统一题目，请重新输入题目数量和分值并选择题目',
      type: 'info'
    })
  } else if (item == 1) {
    ElMessage({
      message: '试卷类型改为随机题目，请重新输入题目数量和分值',
      type: 'info'
    })
  }
}

// 取消的方法
function cancelAddTest () {
  router.push({
    path: 'testpaper'
  })

}

// 清空表单的方法
function clearData () {
  addTestForm.value = {
    paperTitle: '',
    paperType: 0,
    singleChoice: '',
    singleChoiceValue: '',
    multipleChoice: '',
    multipleChoiceValue: '',
    judgeChoice: '',
    judgeChoiceValue: '',
    fillChoice: '',
    fillChoiceValue: '',
    discussChoice: '',
    discussChoiceValue: ''
  }
  localStorage.setItem('addTestForm', JSON.stringify(addTestForm.value))
  try {
    dictStore.clearIds()
  } catch (error) {
  }

}




</script>

<style lang='scss' scoped>
.addTestPaper {
  padding: 32px;
  background: #f5f6f9;
  .container {
    min-height: 936px;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    .addTestTitle {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 88px;
      padding: 0 32px;
      border-bottom: 1px solid #d4d4d4;
      h2 {
        font-size: 22px;
        color: #343957;
      }
      .backBtn {
        width: 80px;
        height: 40px;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #5974ff;
        font-size: 16px;
        color: #5974ff;
      }
    }

    .addTestForm {
      padding: 40px 373px 0 373px;
      ::v-deep(.el-input__wrapper.is-focus) {
        box-shadow: 0 0 0 1px #c0c4cc;
      }

      ::v-deep(.el-form-item__label) {
        font-weight: 400;
        font-size: 16px;
        color: #696969;
      }

      .operateBox {
        margin-top: 80px;
        .btnCancel {
          width: 108px;
          height: 40px;
          border-radius: 6px 6px 6px 6px;
          border: 1px solid #5974ff;
          font-size: 16px;
          color: #5974ff;
        }

        .btnSave {
          width: 108px;
          height: 40px;
          background: #5974ff;
          border-radius: 6px 6px 6px 6px;
          font-size: 16px;
          color: #ffffff;
        }
      }
    }
  }

  .questionSet {
    display: flex;
    margin-top: 10px;
    ::v-deep(.el-input__wrapper) {
      width: 186px;
      height: 36px;
    }

    .chooseQuestionBtn1 {
      width: 112px;
      height: 40px;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #5974ff;
      font-size: 16px;
      color: #5974ff;
      margin-left: 140px;
    }
    .chooseQuestionBtn2 {
      width: 112px;
      height: 40px;
      background: #5974ff;
      border-radius: 6px 6px 6px 6px;
      font-size: 16px;
      color: #ffffff;
      margin-left: 140px;
    }
  }
}
</style>
